package com.elepro.shoppingmall.config.security;

import com.elepro.shoppingmall.config.security.handler.*;
import com.elepro.shoppingmall.service.user.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsUtils;

import javax.annotation.Resource;

//cookie-session认证和授权
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsServiceImpl userDetailsService;
    @Resource
    private SuccessHandler successHandler;
    @Resource
    private FailureHandler failureHandler;
    @Resource
    private AuthenticationHandler authenticationHandler;
    @Resource
    private CanNotAccessHandler canNotAccessHandler;
    @Resource
    private LogoutHandler logoutHandler;

    //加密
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/sendEmailCode").permitAll()
                .antMatchers("/sendEmailCodeToUpdatePassword").permitAll()
                .antMatchers("/checkCodeIsOk").permitAll()
                .antMatchers("/updatePassword").permitAll()
                .antMatchers("/common").hasRole("common")
                .antMatchers("/vip").hasRole("vip")
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                //成功
                .successHandler(successHandler)
                //失败
                .failureHandler(failureHandler)
                .and()
                .exceptionHandling()
                //未登录
                .authenticationEntryPoint(authenticationHandler)
                //权限不足
                .accessDeniedHandler(canNotAccessHandler)
                .and()
                .logout().permitAll()
                //注销成功
                .logoutSuccessHandler(logoutHandler)
                .deleteCookies("JSESSIONID");
    }
}
